﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using BaseData;
using BaseData.Exts;
using BaseData.Models;
using BaseLib.Helper;
using BaseUtility;
using Newtonsoft.Json;
namespace WebUI.Ashx.Acc.Staff
{
    /// <summary>
    /// NewsAdminInfoList 的摘要说明
    /// </summary>
    public class NewsAdminInfoListBck : Base, IHttpHandler
    {
        private static readonly AccClass _accId = new AccExts(new GetAccType().Parse(Request.QueryString["url"])).Instances;
        public void ProcessRequest(HttpContext context)
        {
            if (_accId.Id == 0 || string.IsNullOrWhiteSpace(_accId.Name) || _accId.Type == 0) return;
            using (var ctx = new ContextExt())
            {
                var id = context.Request.QueryString["id"].ToInt(0);
                var sql = from q in ctx.Web_Base_News_Info select q;
                if (id == 0)
                {
                    //sql = sql.OrderByDescending(o => o.PkId);

                }
                else
                {
                    var res = this.GetLowers(ctx, new List<int> { id });
                    // context.Response.Write(JsonConvert.SerializeObject(string.Join(",", res)));
                    sql = sql.Where(w => res.Contains(w.NodeId ?? 0)).OrderByDescending(o => o.SortId);
                }
                var items = sql.Any() ? sql.ToList() : new List<Web_Base_News_Info>();
                context.Response.Write(items.ObjectsToJson());
            }
            context.Response.ContentType = "text/plain";
        }
        private List<int> GetLowers(ContextExt ctx, List<int> ids)
        {
            var items = this.GetLower(ctx, ids);
            if (items.Any()) ids.AddRange(this.GetLowers(ctx, items.ToList()));
            return ids;
        }
        private List<int> GetLower(ContextExt ctx, List<int> ids)
        {
            var items = from q in ctx.Web_Base_News_Node where ids.Contains(q.ParentId ?? 0) select q.PkId;
            return items.Any() ? items.ToList() : new List<int>();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}